package org.wei.p2p.common.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.wei.p2p.common.domain.BusinessException;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static org.wei.p2p.common.domain.CommonErrorCode.E_100103;

/**
 * <P>
 * okHttp3请求工具类
 * </p>
 * @author wei
 */
@Slf4j
public class OkHttpUtil {

	private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient().newBuilder().retryOnConnectionFailure(true)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS).build();

	private static final MediaType JSON_TYPE
			= MediaType.parse("application/json; charset=utf-8");

	/**
	 * 发送post请求
	 * @param url
	 * @param json
	 * @return
	 */
	public static String post(String url, String json) {
		okhttp3.RequestBody body = okhttp3.RequestBody.create(JSON_TYPE, json);
		Request request = new Request.Builder().url(url).post(body).build();
		try (Response response = OK_HTTP_CLIENT.newCall(request).execute()) {
			okhttp3.ResponseBody responseBody = response.body();
			if (responseBody != null) {
				return responseBody.string();
			}
		} catch (IOException e) {
			log.error("请求接口异常", e);
		}
		throw new BusinessException(E_100103);
	}
}
